package com.appkubes.mall.restful.application.plugin.rent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.common.utils.net.HttpClientUtils;
import com.appkubes.mall.core.entity.MallOrder;
import com.appkubes.mall.restful.application.order.order.entity.RentModel;
import com.appkubes.mall.restful.application.order.order.service.impl.OrderServiceImpl;
import com.appkubes.mall.restful.application.order.rent.entity.vo.*;
import com.appkubes.mall.restful.application.plugin.rent.service.PluginRentService;
import com.appkubes.mall.restful.application.plugin.rent.service.PluginRentUrlService;
import com.appkubes.mall.restful.application.wx.model.CreditModel;
import com.appkubes.mall.restful.common.constant.RentOrderPeriodCode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class PluginRentServiceImpl implements PluginRentService {
    @Resource
    PluginRentUrlService rentUrlService;

    @Autowired
    OrderServiceImpl orderServiceImpl;


    private AddRentOrderVO arrKeyToOrderVo(MallOrder order, RentInfoVO rentInfoVO, String goodses) {
        AddRentOrderVO addRentOrderVO = new AddRentOrderVO();
        GoodsInfoVO goodsInfoVO = new GoodsInfoVO();
        ReferInfoVO referInfoVO = new ReferInfoVO();

        RentModel rentModel = orderServiceImpl.getSpecificCode(JSONArray.parseArray(goodses));
        RentOrderPeriodCode rentOrderPeriodCode = RentOrderPeriodCode.valueOf(rentModel.getRentCode());

        rentInfoVO.setPeriodsCode(rentModel.getRentCode());
        rentInfoVO.setPeriodType(rentOrderPeriodCode.getPeriodType());
        rentInfoVO.setPeriods(rentOrderPeriodCode.getPeriods());
        rentInfoVO.setPeriodLong(rentOrderPeriodCode.getPeriodDays());

        goodsInfoVO.setGoodsAmount(rentInfoVO.getRentAmount() + rentInfoVO.getBuyOutAmount());
        goodsInfoVO.setGoodsTitle(rentModel.getGoodsTitle());
        // TODO:加入经纪人
        referInfoVO.setRefChannelId("channelId");
        referInfoVO.setRefChannelName("channelName");
        referInfoVO.setRefGroupId("groupId");
        referInfoVO.setRefGroupName("groupName");
        referInfoVO.setRefUserName("userName");
        referInfoVO.setRefUserPhone("userPhone");

        addRentOrderVO.setRentOrderNo(order.getOrderNo());
        addRentOrderVO.setOrderKey(order.getOrderKey());
        addRentOrderVO.setUserKey(order.getUserKey());
        addRentOrderVO.setGoodsInfoVO(goodsInfoVO);
        addRentOrderVO.setReferInfoVO(referInfoVO);
        addRentOrderVO.setRentInfoVO(rentInfoVO);

        return addRentOrderVO;
    }

    public JSONObject getOrderState(String orderKey) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("orderKey", orderKey);

        Response response = HttpClientUtils.get(rentUrlService.getOrderQueryURL(), map);
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            if (jsonObject.getInteger("code") != 200) {
                throw new Exception(jsonObject.getString("message"));
            }
            return jsonObject.getJSONObject("data");
        }
        throw new Exception("租赁下单失败");
    }

    public JSONObject shipOrder(String orderKey, String userKey, Integer isPayFirst) throws RuntimeException {
        log.info("notify rent module: shipOrder:" + orderKey + "," + ", userKey:" + userKey + ", isPayFirst:" + isPayFirst);
        System.out.println("notify rent module: shipOrder:" + orderKey + "," + ", userKey:" + userKey + ", isPayFirst:" + isPayFirst);
        Map<String, String> map = new HashMap<>();
        map.put("orderKey", orderKey);
        map.put("userKey", userKey);
        map.put("isPayFirst", isPayFirst.toString());
        String str = HttpClientUtils.postForBody(rentUrlService.getOrderShipURL(), map);
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            log.info("notify rent module get response: " + jsonObject.toJSONString());
            if (jsonObject.getInteger("code") == 200) {
                return jsonObject;
            }
            throw new RuntimeException(jsonObject.getString("message"));
        }
        throw new RuntimeException("租赁订单收货失败");
    }

    public JSONObject addZuLinOrder(MallOrder order, RentInfoVO rentInfoVO, String goodses) throws Exception {
        AddRentOrderVO orderVo = arrKeyToOrderVo(order, rentInfoVO, goodses);
        String beanString = JSONObject.toJSONString(orderVo);
        System.out.println(beanString);
        Response response = HttpClientUtils.post(rentUrlService.getOrderAddURL(), beanString);
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            System.out.println(jsonObject);
            if (jsonObject.getInteger("code") != 200) {
                throw new Exception(jsonObject.getString("message"));
            }
            return jsonObject;
        }
        throw new Exception("租赁下单失败");
    }

    public JSONObject cancelZuLinOrder(CreditModel creditModel) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("orderKey", creditModel.getOrderKey());
        map.put("userKey", creditModel.getUserKey());

        String str = HttpClientUtils.postForBody(rentUrlService.getOrderCancelURL(), map);
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            log.info(jsonObject.toJSONString());
            if (jsonObject.getInteger("code") != 200) {
                throw new Exception(jsonObject.getString("message"));
            }
            return jsonObject;
        }
        throw new Exception("租赁订单取消失败");
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public JSONObject paySucOrder(String orderKey) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("orderKey", orderKey);
        log.info("getOrderPayURL parameter: {}", map);


        Response response = HttpClientUtils.post(rentUrlService.getOrderPayURL(), map);
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            log.info(jsonObject.toJSONString());
            if (jsonObject.getInteger("code") == 200) {
                return jsonObject;
            }
            log.error("paySucOrder: " + jsonObject.getString("message"));
            throw new Exception(jsonObject.getString("message"));
        }
        log.error("租赁订单回调失败: EMPTY ");
        throw new Exception("租赁订单回调失败");
    }

    @Override
    public JSONObject queryRentOrder(String orderKey) throws IOException,RuntimeException {
        String queryUrl = String.format(rentUrlService.getRentOrderQueryURL()+"?orderKey=%s", orderKey);
        Response response = HttpClientUtils.get(queryUrl);
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            log.info(jsonObject.toJSONString());
            if (jsonObject.getInteger("code") == 200) {
                return jsonObject;
            }
            throw  new RuntimeException(jsonObject.getString("message"));
        }
        throw new RuntimeException("租赁下单失败");
    }
}
